package com.longway.common.kit;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.digest.DigestUtils;
import com.jfinal.kit.Base64Kit;

public class AesKit {
	
		/**
		 * 加密
		 * 
		 * @param content    加密的字符串
		 * @param encryptKey key值
		 * @return
		 * @throws Exception
		 */
		public static String encrypt(String content, String encryptKey) throws Exception {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128);
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
			byte[] b = cipher.doFinal(content.getBytes("utf-8"));
			// 采用base64算法进行转码,避免出现中文乱码
			return Base64Kit.encode(b);
		}

		/**
		 * 解密
		 * 
		 * @param encryptStr 解密的字符串
		 * @param decryptKey 解密的key值
		 * @return
		 * @throws Exception
		 */
		public static String decrypt(String encryptStr, String decryptKey) throws Exception {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128);
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
			// 采用base64算法进行转码,避免出现中文乱码
			byte[] encryptBytes = Base64Kit.decode(encryptStr);
			byte[] decryptBytes = cipher.doFinal(encryptBytes);
			return new String(decryptBytes);
		}
}
